package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import exception.DatabaseConnectException;

public class Conexao {

	private static Conexao inst = null;
	private static Connection conexao = null;

	private Conexao() {

	}

	public static Conexao getInst() throws DatabaseConnectException {
		if (inst == null) {
			inst = new Conexao();

			if (conexao == null) {
				try {
					Class.forName("org.postgresql.Driver");
					conexao = DriverManager.getConnection(
							"jdbc:postgresql://localhost:5432/maindatabase",
							"postgres", "postgres");
				} catch (ClassNotFoundException eSQL) {
					throw new DatabaseConnectException(eSQL,
							DatabaseConnectException.CONNECT);
				} catch (SQLException e) {
					throw new DatabaseConnectException(e,
							DatabaseConnectException.CONNECT);
				}
			}
		}
		return inst;
	}

	public Connection getConnection() throws DatabaseConnectException {
		return conexao;
	}

	public void desconectaBanco(Connection connection)
			throws DatabaseConnectException {
		try {
			connection.close();
		} catch (SQLException eSQL) {
			throw new DatabaseConnectException(eSQL,
					DatabaseConnectException.DISCONNECT);
		}
	}
}